import java.util.Arrays;

public class HeapSort {
    public static void main(String[] args) {
        int[] nums={6,5,4,3,2,1,0};
        sort(nums);
        System.out.println(Arrays.toString(nums));
    }
    public static void sort(int[] nums) {
        //先建立一个大顶堆
        buildBigHeap(nums);
        //大顶堆的第一个永远是最大的，和最后一个调整，然后调整
        for (int i = 1; i < nums.length; i++) {
            swap(nums, 0, nums.length - i);
            adjust(nums, 0, nums.length - i);
        }
    }

    private static void buildBigHeap(int[] nums) {
        for (int i = (nums.length / 2); i >= 0; i--) {
            adjust(nums, i, nums.length);
        }
    }

    private static void adjust(int[] nums, int target, int end) {
        while (target < end) {
            int left = 2 * target + 1;
            int right = 2 * target + 2;
            if(left>=end) break;
            int max = left;
            if (right < end && nums[right] > nums[left]) {
                max = right;
            }
            if (nums[target] < nums[max]) {
                swap(nums, target, max);
            }
            target = max;
        }
    }

    private static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

}
